package section5_3;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hyman on 2017/6/9.
 */
public class LineTask extends RecursiveTask<Integer> {

    /**
     * 文档中一行数据
     */
    private String line[];

    /**
     * 行处理的起始位置
     */
    private int start;
    /**
     * 行处理的结束位置
     */
    private int end;

    /**
     * 要查找的单词
     */
    private String word;

    public LineTask(String line[], int start, int end, String word) {
        this.line = line;
        this.start = start;
        this.end = end;
        this.word = word;
    }

    @Override
    protected Integer compute() {

        Integer result = null;

        if(end - start < 100) {
            result = count(line, start, end, word);
        } else {
            int mid = (start + end) / 2;
            LineTask task1 = new LineTask(line, start, mid+1, word);
            LineTask task2 = new LineTask(line, mid+1, end, word);
            invokeAll(task1, task2);

            try {
                result = groupResults(task1.get(), task2.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 返回number1+number2的和
     *
     * @param number1
     * @param number2
     * @return
     */
    private Integer groupResults(Integer number1, Integer number2) {
        return number1 + number2;
    }

    private Integer count(String[] line, int start, int end, String word) {
        int counter = 0;
        for(int i=start; i<end; i++) {
            if(line[i].equals(word)) {
                counter++;
            }
        }
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return counter;
    }
}
